package com.example.provider.serviceImpl;

import com.example.api.service.UserService;
import com.example.provider.dao.UserDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.api.entity.User;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.List;



@Slf4j
@Service(version = "1.0.0",timeout = 3000)
public class UserServiceImpl implements UserService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserDao userDao;

    private List<User> users;

    @Override
    public void insertUser(User user){

        userDao.save(user);
    }

    @Override
    public void deleteUser(Integer id){

        userDao.deleteById(id);
    }

    @Override
    public void updateUser(User user){

        userDao.save(user);
    }

    @Override
    public List<User> getUser(){

        return (List<User>) userDao.findAll();
    }

    @Override
    public User getUserById(Integer id){
        User user=(User) redisTemplate.opsForValue().get(id.toString());
        if (user == null){
            log.info("缓存中没有，需要从数据库中读取");
            User user1=userDao.findById(id).get();

            //设置key为字符串序列化方式
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            //设置序列化valued的实例化对象
            redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
            //hash的key也采用string的序列化方式
            redisTemplate.setHashKeySerializer(new StringRedisSerializer());
            //hash的value序列化方式采用jackon
            redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

            redisTemplate.opsForValue().set(id.toString(),user1);
            log.info("已放入缓存，下次可直接从缓存中获取");
            return user1;
        }
        return userDao.findById(id).get();
    }
}

